package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.web.app.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.aliyun.teautil.Common.assertAsString;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private Client client;

    @Override
    public void sendCode(String phone, String code) {
        //参数
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                //签名
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        SendSmsResponse response = null;
        try {
            response = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            throw new LeaseException(ResultCodeEnum.SMS_ERROR);
        }

        SendSmsResponseBody body = response.getBody();
        String responseCode = body.getCode();
        //如果失败了
        if (!"OK".equals(responseCode)) {
            //流控
            if ("isv.BUSINESS_LIMIT_CONTROL".equals(responseCode)) {
                //验证码发送频繁
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            } else {
                //服务器错误
                throw new LeaseException(ResultCodeEnum.SMS_ERROR);
            }
        }

    }
}
